import {PureComponent} from "react";
import {StoreContext} from "./StoreCotext";

// 高阶函数，返回=>高阶组件
export function connect(mapStateToProps, mapDispatchToProps) {
    return function (WrapperComponent) {
        class NewComponent extends PureComponent {
            constructor(props, context) {
                super(props);
                this.state = mapStateToProps(context.getState())
            }

            componentDidMount() {
                this.onSubscribe = this.context.subscribe(() => {
                    this.setState(mapStateToProps(this.context.getState()))
                })
            }

            componentWillUnmount() {
                this.onSubscribe && this.onSubscribe()
            }

            render() {
                const stateObj = mapStateToProps(this.context.getState());
                const dispatchObj = mapDispatchToProps(this.context.dispatch)
                return (
                    <WrapperComponent {...this.props} {...stateObj} {...dispatchObj}/>
                )
            }
        }

        NewComponent.contextType = StoreContext

        return NewComponent;
    }
}